<template>
  <view class="search-page">
    <!-- 搜索栏 -->
    <view class="search-header">
      <view class="search-input-wrapper">
        <input 
          v-model="searchKeyword"
          class="search-input"
          placeholder="搜索课程名称、机构名称"
          confirm-type="search"
          @confirm="handleSearch"
          @input="onInputChange"
        />
        <view class="search-icon" @click="handleSearch">
          🔍
        </view>
      </view>
      <text class="cancel-btn" @click="goBack">取消</text>
    </view>

    <!-- 搜索建议 -->
    <view class="search-suggestions" v-if="showSuggestions && suggestions.length > 0">
      <view 
        v-for="suggestion in suggestions" 
        :key="suggestion"
        class="suggestion-item"
        @click="selectSuggestion(suggestion)"
      >
        <text class="suggestion-text">{{ suggestion }}</text>
      </view>
    </view>

    <!-- 搜索历史 -->
    <view class="search-history" v-if="!searchKeyword && searchHistory.length > 0">
      <view class="history-header">
        <text class="history-title">搜索历史</text>
        <text class="clear-btn" @click="clearHistory">清空</text>
      </view>
      <view class="history-tags">
        <text 
          v-for="item in searchHistory" 
          :key="item"
          class="history-tag"
          @click="selectHistory(item)"
        >
          {{ item }}
        </text>
      </view>
    </view>

    <!-- 热门搜索 -->
    <view class="hot-search" v-if="!searchKeyword && hotKeywords.length > 0">
      <view class="hot-title">热门搜索</view>
      <view class="hot-tags">
        <text 
          v-for="keyword in hotKeywords" 
          :key="keyword"
          class="hot-tag"
          @click="selectHotKeyword(keyword)"
        >
          {{ keyword }}
        </text>
      </view>
    </view>

    <!-- 搜索结果 -->
    <view class="search-results" v-if="hasSearched">
      <!-- 筛选栏 -->
      <view class="filter-bar">
        <view class="filter-item" @click="showSortModal">
          <text class="filter-text">{{ currentSort.label }}</text>
          <text class="filter-arrow">▼</text>
        </view>
        <view class="filter-item" @click="showCategoryModal">
          <text class="filter-text">{{ currentCategory.label }}</text>
          <text class="filter-arrow">▼</text>
        </view>
        <view class="filter-item" @click="showPriceModal">
          <text class="filter-text">{{ currentPrice.label }}</text>
          <text class="filter-arrow">▼</text>
        </view>
      </view>

      <!-- 结果统计 -->
      <view class="result-stats">
        <text>找到 {{ totalCount }} 个相关课程</text>
      </view>

      <!-- 课程列表 -->
      <view class="course-list" v-if="courseList.length > 0">
        <view 
          v-for="course in courseList" 
          :key="course.id"
          class="course-item"
          @click="goToCourseDetail(course.id)"
        >
          <image :src="course.coverUrl" class="course-image" mode="aspectFill" />
          <view class="course-info">
            <text class="course-title">{{ course.title }}</text>
            <text class="course-desc">{{ course.description }}</text>
            <view class="course-meta">
              <text class="merchant-name">{{ course.merchantName }}</text>
              <view class="course-stats">
                <text class="student-count">{{ course.studentCount }}人学过</text>
                <text class="rating">{{ course.rating }}分</text>
              </view>
            </view>
            <view class="course-price">
              <text class="current-price">¥{{ course.currentPrice }}</text>
              <text v-if="course.originalPrice > course.currentPrice" class="original-price">
                ¥{{ course.originalPrice }}
              </text>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-result" v-else-if="!loading">
        <image src="../../static/images/empty-search.png" class="empty-image" />
        <text class="empty-text">没有找到相关课程</text>
        <text class="empty-tip">试试其他关键词吧</text>
      </view>

      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMore && courseList.length > 0">
        <button class="load-more-btn" @click="loadMore" :loading="loadingMore">
          {{ loadingMore ? '加载中...' : '加载更多' }}
        </button>
      </view>
    </view>

    <!-- 排序弹窗 -->
    <view class="modal-overlay" v-if="showSortOptions" @click="hideSortModal">
      <view class="modal-content" @click.stop>
        <view class="modal-title">排序方式</view>
        <view class="option-list">
          <view 
            v-for="option in sortOptions" 
            :key="option.value"
            class="option-item"
            :class="{ active: currentSort.value === option.value }"
            @click="selectSort(option)"
          >
            <text class="option-text">{{ option.label }}</text>
            <text v-if="currentSort.value === option.value" class="option-check">✓</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 分类弹窗 -->
    <view class="modal-overlay" v-if="showCategoryOptions" @click="hideCategoryModal">
      <view class="modal-content" @click.stop>
        <view class="modal-title">课程分类</view>
        <view class="option-list">
          <view 
            v-for="option in categoryOptions" 
            :key="option.value"
            class="option-item"
            :class="{ active: currentCategory.value === option.value }"
            @click="selectCategory(option)"
          >
            <text class="option-text">{{ option.label }}</text>
            <text v-if="currentCategory.value === option.value" class="option-check">✓</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 价格弹窗 -->
    <view class="modal-overlay" v-if="showPriceOptions" @click="hidePriceModal">
      <view class="modal-content" @click.stop>
        <view class="modal-title">价格区间</view>
        <view class="option-list">
          <view 
            v-for="option in priceOptions" 
            :key="option.value"
            class="option-item"
            :class="{ active: currentPrice.value === option.value }"
            @click="selectPrice(option)"
          >
            <text class="option-text">{{ option.label }}</text>
            <text v-if="currentPrice.value === option.value" class="option-check">✓</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import Taro from '@tarojs/taro'
import courseApi from '@/api/course'
import { debounce, showLoading, hideLoading, showError, navigateTo } from '@/utils'

// 响应式数据
const searchKeyword = ref('')
const suggestions = ref([])
const showSuggestions = ref(false)
const searchHistory = ref([])
const hotKeywords = ref([])
const hasSearched = ref(false)
const loading = ref(false)
const loadingMore = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)
const courseList = ref([])

// 筛选选项
const showSortOptions = ref(false)
const showCategoryOptions = ref(false)
const showPriceOptions = ref(false)

const currentSort = ref({ label: '综合排序', value: 'default' })
const currentCategory = ref({ label: '全部分类', value: '' })
const currentPrice = ref({ label: '全部价格', value: '' })

const sortOptions = ref([
  { label: '综合排序', value: 'default' },
  { label: '价格从低到高', value: 'price_asc' },
  { label: '价格从高到低', value: 'price_desc' },
  { label: '销量最高', value: 'sales_desc' },
  { label: '评分最高', value: 'rating_desc' }
])

const categoryOptions = ref([
  { label: '全部分类', value: '' }
])

const priceOptions = ref([
  { label: '全部价格', value: '' },
  { label: '0-100元', value: '0-100' },
  { label: '100-500元', value: '100-500' },
  { label: '500-1000元', value: '500-1000' },
  { label: '1000元以上', value: '1000-' }
])

// 页面加载
onMounted(() => {
  loadSearchHistory()
  loadHotKeywords()
  loadCategories()
})

// 监听搜索关键词变化
watch(searchKeyword, debounce((newVal) => {
  if (newVal.trim()) {
    loadSuggestions(newVal)
    showSuggestions.value = true
  } else {
    showSuggestions.value = false
    suggestions.value = []
  }
}, 300))

// 加载搜索历史
const loadSearchHistory = () => {
  try {
    const history = Taro.getStorageSync('searchHistory') || []
    searchHistory.value = history.slice(0, 10) // 最多显示10条
  } catch (error) {
    console.error('加载搜索历史失败:', error)
  }
}

// 保存搜索历史
const saveSearchHistory = (keyword) => {
  try {
    let history = Taro.getStorageSync('searchHistory') || []
    
    // 移除重复项
    history = history.filter(item => item !== keyword)
    
    // 添加到开头
    history.unshift(keyword)
    
    // 最多保存20条
    history = history.slice(0, 20)
    
    Taro.setStorageSync('searchHistory', history)
    searchHistory.value = history.slice(0, 10)
  } catch (error) {
    console.error('保存搜索历史失败:', error)
  }
}

// 清空搜索历史
const clearHistory = () => {
  Taro.showModal({
    title: '确认清空',
    content: '确定要清空搜索历史吗？',
    success: (res) => {
      if (res.confirm) {
        try {
          Taro.removeStorageSync('searchHistory')
          searchHistory.value = []
        } catch (error) {
          console.error('清空搜索历史失败:', error)
        }
      }
    }
  })
}

// 加载热门关键词
const loadHotKeywords = async () => {
  try {
    const result = await courseApi.getHotKeywords()
    
    if (result.code === 200) {
      hotKeywords.value = result.data || []
    }
  } catch (error) {
    console.error('加载热门关键词失败:', error)
  }
}

// 加载分类
const loadCategories = async () => {
  try {
    const result = await courseApi.getCourseCategories()
    
    if (result.code === 200) {
      const categories = result.data || []
      categoryOptions.value = [
        { label: '全部分类', value: '' },
        ...categories.map(cat => ({ label: cat.name, value: cat.id }))
      ]
    }
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

// 加载搜索建议
const loadSuggestions = async (keyword) => {
  try {
    const result = await courseApi.getSearchSuggestions(keyword)
    
    if (result.code === 200) {
      suggestions.value = result.data || []
    }
  } catch (error) {
    console.error('加载搜索建议失败:', error)
  }
}

// 输入变化
const onInputChange = (e) => {
  searchKeyword.value = e.detail.value
}

// 执行搜索
const handleSearch = () => {
  const keyword = searchKeyword.value.trim()
  if (!keyword) return
  
  showSuggestions.value = false
  saveSearchHistory(keyword)
  searchCourses()
}

// 选择搜索建议
const selectSuggestion = (suggestion) => {
  searchKeyword.value = suggestion
  showSuggestions.value = false
  saveSearchHistory(suggestion)
  searchCourses()
}

// 选择搜索历史
const selectHistory = (item) => {
  searchKeyword.value = item
  searchCourses()
}

// 选择热门关键词
const selectHotKeyword = (keyword) => {
  searchKeyword.value = keyword
  saveSearchHistory(keyword)
  searchCourses()
}

// 搜索课程
const searchCourses = async (isLoadMore = false) => {
  try {
    if (!isLoadMore) {
      loading.value = true
      currentPage.value = 1
      courseList.value = []
      hasSearched.value = true
    } else {
      loadingMore.value = true
    }

    const params = {
      keyword: searchKeyword.value.trim(),
      page: currentPage.value,
      pageSize: pageSize.value,
      sortBy: currentSort.value.value,
      categoryId: currentCategory.value.value,
      priceRange: currentPrice.value.value
    }

    const result = await courseApi.searchCourse(params)
    
    if (result.code === 200) {
      const newList = result.data.list || []
      
      if (isLoadMore) {
        courseList.value = [...courseList.value, ...newList]
      } else {
        courseList.value = newList
      }
      
      totalCount.value = result.data.total || 0
      hasMore.value = newList.length === pageSize.value
      currentPage.value++
    }
  } catch (error) {
    console.error('搜索失败:', error)
    showError('搜索失败，请重试')
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

// 显示排序弹窗
const showSortModal = () => {
  showSortOptions.value = true
}

// 隐藏排序弹窗
const hideSortModal = () => {
  showSortOptions.value = false
}

// 选择排序
const selectSort = (option) => {
  currentSort.value = option
  showSortOptions.value = false
  searchCourses()
}

// 显示分类弹窗
const showCategoryModal = () => {
  showCategoryOptions.value = true
}

// 隐藏分类弹窗
const hideCategoryModal = () => {
  showCategoryOptions.value = false
}

// 选择分类
const selectCategory = (option) => {
  currentCategory.value = option
  showCategoryOptions.value = false
  searchCourses()
}

// 显示价格弹窗
const showPriceModal = () => {
  showPriceOptions.value = true
}

// 隐藏价格弹窗
const hidePriceModal = () => {
  showPriceOptions.value = false
}

// 选择价格
const selectPrice = (option) => {
  currentPrice.value = option
  showPriceOptions.value = false
  searchCourses()
}

// 加载更多
const loadMore = () => {
  if (!loadingMore.value && hasMore.value) {
    searchCourses(true)
  }
}

// 跳转课程详情
const goToCourseDetail = (courseId) => {
  navigateTo('/pages/course/detail', { id: courseId })
}

// 返回
const goBack = () => {
  Taro.navigateBack()
}
</script>

<style lang="less">
.search-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-header {
  background: white;
  padding: 16px 32px;
  display: flex;
  align-items: center;
  gap: 24px;

  .search-input-wrapper {
    flex: 1;
    position: relative;
    background: #f8f9fa;
    border-radius: 24px;
    padding: 0 48px 0 32px;

    .search-input {
      width: 100%;
      height: 72px;
      font-size: 28px;
      border: none;
      background: transparent;
    }

    .search-icon {
      position: absolute;
      right: 24px;
      top: 50%;
      transform: translateY(-50%);
      font-size: 32px;
      color: #666;
    }
  }

  .cancel-btn {
    font-size: 28px;
    color: #3478F6;
  }
}

.search-suggestions {
  background: white;
  border-top: 1px solid #f0f0f0;

  .suggestion-item {
    padding: 24px 32px;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .suggestion-text {
      font-size: 28px;
      color: #333;
    }
  }
}

.search-history,
.hot-search {
  background: white;
  margin-top: 16px;
  padding: 32px;

  .history-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    .history-title {
      font-size: 28px;
      font-weight: 500;
      color: #333;
    }

    .clear-btn {
      font-size: 24px;
      color: #666;
    }
  }

  .hot-title {
    font-size: 28px;
    font-weight: 500;
    color: #333;
    margin-bottom: 24px;
  }

  .history-tags,
  .hot-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;

    .history-tag,
    .hot-tag {
      background: #f8f9fa;
      color: #666;
      padding: 16px 24px;
      border-radius: 20px;
      font-size: 24px;
    }
  }
}

.search-results {
  .filter-bar {
    background: white;
    padding: 24px 32px;
    display: flex;
    gap: 32px;
    border-bottom: 1px solid #f0f0f0;

    .filter-item {
      display: flex;
      align-items: center;
      gap: 8px;

      .filter-text {
        font-size: 28px;
        color: #333;
      }

      .filter-arrow {
        font-size: 20px;
        color: #666;
      }
    }
  }

  .result-stats {
    background: white;
    padding: 16px 32px;
    font-size: 24px;
    color: #666;
    border-bottom: 1px solid #f0f0f0;
  }

  .course-list {
    background: white;
    padding: 0 32px;

    .course-item {
      display: flex;
      padding: 32px 0;
      border-bottom: 1px solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .course-image {
        width: 200px;
        height: 150px;
        border-radius: 12px;
        flex-shrink: 0;
      }

      .course-info {
        flex: 1;
        margin-left: 24px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .course-title {
          font-size: 28px;
          font-weight: 500;
          color: #333;
          line-height: 1.4;
          margin-bottom: 8px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }

        .course-desc {
          font-size: 24px;
          color: #666;
          line-height: 1.4;
          margin-bottom: 16px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }

        .course-meta {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;

          .merchant-name {
            font-size: 24px;
            color: #666;
          }

          .course-stats {
            display: flex;
            gap: 16px;

            .student-count,
            .rating {
              font-size: 20px;
              color: #999;
            }
          }
        }

        .course-price {
          display: flex;
          align-items: baseline;
          gap: 16px;

          .current-price {
            font-size: 32px;
            font-weight: 600;
            color: #F5A623;
          }

          .original-price {
            font-size: 24px;
            color: #999;
            text-decoration: line-through;
          }
        }
      }
    }
  }
}

.empty-result {
  text-align: center;
  padding: 120px 40px;

  .empty-image {
    width: 200px;
    height: 200px;
    margin-bottom: 32px;
  }

  .empty-text {
    font-size: 28px;
    color: #333;
    display: block;
    margin-bottom: 16px;
  }

  .empty-tip {
    font-size: 24px;
    color: #999;
    display: block;
  }
}

.load-more {
  padding: 32px;
  text-align: center;

  .load-more-btn {
    background: #f8f9fa;
    color: #666;
    border: none;
    border-radius: 24px;
    padding: 16px 48px;
    font-size: 28px;
  }
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: flex-end;

  .modal-content {
    background: white;
    width: 100%;
    border-radius: 24px 24px 0 0;
    padding: 32px;
    max-height: 60vh;
    overflow-y: auto;

    .modal-title {
      font-size: 32px;
      font-weight: 600;
      color: #333;
      text-align: center;
      margin-bottom: 32px;
    }

    .option-list {
      .option-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 24px 0;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        &.active {
          .option-text {
            color: #3478F6;
          }
        }

        .option-text {
          font-size: 28px;
          color: #333;
        }

        .option-check {
          font-size: 28px;
          color: #3478F6;
        }
      }
    }
  }
}
</style>